package com.atguigu.gulimall.search.service.impl;

import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import com.atguigu.gulimall.search.vo.feign.product.AttrRespVo;
import com.atguigu.gulimall.search.vo.feign.product.BrandVo;
import com.atguigu.gulimall.search.vo.feign.product.CategoryVo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {


    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private ProductFeignService productFeignService;

    @SneakyThrows
    @Override
    public SearchResult search(SearchParam param) {
        SearchRequest searchRequest = buildSearchRequest(param);
        SearchResponse response = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        return buildSearchResult(param, response);
    }

    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder source = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键词
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // catalogId
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // brandId
        if (param.getBrandId() != null && !param.getBrandId().isEmpty()) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // nested 属性
        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder query = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValue = s[1].split(":");
                query.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                query.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
                // 每一个都得生成nested 查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", query, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }

        // hasStock：是否有库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }


        // 按照价格区间查询
        // todo mapping 中 skuPrice 类型为keyword，采用字符串比较法，不是数值比较
        String skuPrice = param.getSkuPrice();
        if (!StringUtils.isEmpty(skuPrice)) {
            String[] s = skuPrice.split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (!StringUtils.isEmpty(s[0])) {
                rangeQuery.gte(Integer.parseInt(s[0]));
            }
            if (!StringUtils.isEmpty(s[1])) {
                rangeQuery.lte(Integer.parseInt(s[1]));
            }
            boolQuery.filter(rangeQuery);
        }


        source.query(boolQuery);

        // 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder order = "asc".equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            source.sort(s[0], order);
        }

        // 分页
        int form = (param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE;
        source.from(form).size(EsConstant.PRODUCT_PAGE_SIZE);

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<b style='color: red'>");
        highlightBuilder.postTags("</b>");
        source.highlighter(highlightBuilder);

        // 聚合部分
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_image_agg").field("brandImg").size(1));
        source.aggregation(brandAgg);

        // 类别聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        source.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出所有的 属性id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        attr_id_agg.subAggregation(attr_name_agg);
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1);
        attr_id_agg.subAggregation(attr_value_agg);
        nested.subAggregation(attr_id_agg);
        source.aggregation(nested);

//        log.info("包装的dsl语句为：{}", source);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, source);
    }

    @SneakyThrows
    private SearchResult buildSearchResult(SearchParam param, SearchResponse response) {
        SearchResult result = new SearchResult();

        // 设置查询商品信息
        SearchHits hits = response.getHits();
        List<SkuEsModel> products = new ArrayList<>();
        if (hits.getTotalHits().value > 0) {
            for (SearchHit hit : hits.getHits()) {
                String dataStr = hit.getSourceAsString();
                SkuEsModel skuEsModel = objectMapper.readValue(dataStr, SkuEsModel.class);
                if (param.getKeyword() != null) {
                    // 设置高亮
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }

                products.add(skuEsModel);
            }
        } else {
            return null;
        }

        result.setProducts(products);

        // 设置类别信息
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            long catalogId = bucket.getKeyAsNumber().longValue();
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().get("catalog_name_agg")).getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogs.add(catalogVo);
        }
        result.setCatalogs(catalogs);

        // 设置属性信息
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            long attrId = bucket.getKeyAsNumber().longValue();
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg"))
                    .getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValues(attrValue);
            attrs.add(attrVo);
        }

        result.setAttrs(attrs);

        long total = hits.getTotalHits().value;
        // 总记录数
        result.setTotal(total);

        // 品牌信息
        List<SearchResult.BrandVo> brands = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            long brandId = bucket.getKeyAsNumber().longValue();
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_image_agg")).getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brands.add(brandVo);
        }

        result.setBrands(brands);

        // 当前页码
        result.setPageNum(param.getPageNum());
        Long totalPage = total % EsConstant.PRODUCT_PAGE_SIZE == 0 ? total / EsConstant.PRODUCT_PAGE_SIZE : 1 + (total / EsConstant.PRODUCT_PAGE_SIZE);
        // 总页码
        result.setTotalPages(totalPage);
        List<Integer> pageNav = IntStream.range(1, totalPage.intValue()).boxed().collect(Collectors.toList());
        result.setPageNav(pageNav);

        // 设置面包屑导航数据1
        if (param.getAttrs() != null) {
            List<SearchResult.NavVo> navVos = param.getAttrs().stream()
                    .map(attr -> {
                        SearchResult.NavVo navVo = new SearchResult.NavVo();
                        String[] s = attr.split("_");
                        navVo.setNavValue(s[1]);
                        R r = productFeignService.attrInfo(Long.valueOf(s[0]));
                        result.getAttrIds().add(Long.valueOf(s[0]));
                        if (r.isOk()) {
                            AttrRespVo data = r.getData("attr", new TypeReference<AttrRespVo>() {
                            });
                            navVo.setNavName(data.getAttrName());
                        } else {
                            navVo.setNavName(s[0]);
                        }
                        // 取消面包屑后，要跳转到那个地方
                        String replace = replaceQueryString(param, attr, "attrs");
                        navVo.setNavLink("http://search.gulimall.com/list.html?" + replace);
                        return navVo;
                    }).collect(Collectors.toList());
            result.setNavVos(navVos);
        }


        /// 品牌与分类
        if (param.getBrandId() != null && !param.getBrandId().isEmpty()) {
            // 存在品牌查询信息
            List<SearchResult.NavVo> navVos = result.getNavVos();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            R r = productFeignService.brandInfo(param.getBrandId());
            if (r.isOk()) {
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuilder sb = new StringBuilder();
                for (BrandVo brandVo : brand) {
                    String brandName = brandVo.getName();
                    sb.append(brandName);
                    String qs = replaceQueryString(param, brandVo.getBrandId().toString(), "brandId");
                    navVo.setNavLink("http://search.gulimall.com/list.html?" + qs);
                }
                navVo.setNavValue(sb.toString());
            }
            navVos.add(navVo);
        }
        // TODO: 分类筛选
        if (param.getCatalog3Id() != null) {
            // 存在品牌查询信息
            List<SearchResult.NavVo> navVos = result.getNavVos();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("分类");
            R r = productFeignService.catalogInfo(param.getCatalog3Id());
            if (r.isOk()) {
                CategoryVo categoryVo = r.getData(new TypeReference<CategoryVo>() {
                });
                navVo.setNavValue(categoryVo.getName());
                String qs = replaceQueryString(param, categoryVo.getCatId().toString(), "catalog3Id");
                navVo.setNavLink("http://search.gulimall.com/list.html?" + qs);
            }
            navVos.add(navVo);
        }


        return result;
    }

    private static String replaceQueryString(SearchParam param, String attrValue, String attrName) {
        String encode;
        try {
            // 浏览器和java对空格编码不一样
            encode = URLEncoder.encode(attrValue, "UTF-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return param.getQueryString().replace("&" + attrName + "=" + encode, "");
    }


}
